#include "Util.h"

// --- SQL操作类 ---
SqlUtil::SqlUtil(const QString &host, const QString &dbName, const QString &user_name, QString &password)
    : _host_name(host), _database_name(dbName), _user_name(user_name), _password(password)
{
    _db = QSqlDatabase::addDatabase("QMYSQL");
    _db.setHostName(_host_name);
    _db.setDatabaseName(_database_name);
    _db.setPassword(_password);
    _db.setUserName(_user_name);
}

void SqlUtil::closeMySql()
{
    QSqlDatabase::database().close();
    qDebug() << "数据库连接已关闭";
}

bool SqlUtil::connectMySql()
{
    _db.setHostName(_host_name);
    _db.setUserName(_user_name);
    _db.setPassword(_password);
    _db.setDatabaseName(_database_name);
    _db.setPort(3306);
    if(!_db.open()){
        QMessageBox::warning(nullptr, "Error", "Unable to connect to database: " + _db.lastError().text());
        return false;
    }else{
        qDebug() << "成功链接到数据库";
        return true;
    }
}

// --- 字符串操作类 ---
void StringUtil::SplitString(const QString &str, std::vector<QString> &result, char delimiter) {
    result.clear();
    QStringList parts = str.split(delimiter);
    for (const auto& part : parts) {
        result.push_back(part);
    }
}

// --- 数据库管理类 ---
DatabasesManager::DatabasesManager(const QString& host, const QString& dbName, const QString& user_name, QString& password)
    : _host_name(host), _database_name(dbName), _user_name(user_name), _password(password)
{
    _db = QSqlDatabase::addDatabase("QMYSQL");
    _db.setHostName(_host_name);
    _db.setDatabaseName(_database_name);
    _db.setPassword(_password);
    _db.setUserName(_user_name);
}

bool DatabasesManager::open()
{
    if (!_db.open()) {
       qDebug() << "Error: Unable to connect to the database." << _db.lastError().text();
       return false;
    }
    return true;
}

void DatabasesManager::close()
{
    if(_db.isOpen())
    {
        _db.close();
    }
}

bool DatabasesManager::executeQuery(const QString &sqlStr)
{
    QSqlQuery query;
    if(!query.exec(sqlStr)) {
         qDebug() << "Query execution error:" << query.lastError().text();
         return false;
    }
    return true;
}

QSqlQuery DatabasesManager::executeQueryWithResults(const QString &sqlStr)
{
    QSqlQuery query;
   if (!query.exec(sqlStr)) {
       qDebug() << "Query execution error:" << query.lastError().text();
   }
    return query;
}
